package com.muqi.server.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.muqi.server.common.auth.DoubleToken;
import com.muqi.server.common.response.ResponseClass;
import com.muqi.server.common.utilis.UserUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@ConditionalOnClass(DispatcherServlet.class)
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(200);
            return false;
        }

        String token = request.getHeader("Authorization");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        if (StrUtil.isBlank(token)) {
            if (request.getRequestURI().contains("/user/login") || request.getRequestURI().contains("/user/register") || request.getRequestURI().contains("/user/refreshToken")) {
                UserUtil.setUser(-1, -1);
                return true;
            } else {
                response.setStatus(200);
                response.getWriter().write(new ResponseClass(401, null, "未登录").toString());
                return false;
            }
        } else {
            if (!DoubleToken.verifyAccessToken(token)) {
                response.setStatus(200);
                response.getWriter().write(new ResponseClass(419, null, "AccessToken过期，请刷新").toString());
                return false;
            } else {
                Integer userId = DoubleToken.getID(token);
                Integer type = DoubleToken.getType(token);
                UserUtil.setUser(userId, type);
                return true;
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }



}
